package com.blb.service.impl;

import com.blb.entity.ComImg;
import com.blb.entity.Commodity;
import com.blb.entity.TypeCom;
import com.blb.mapper.ComImgMapper;
import com.blb.mapper.CommodityMapper;
import com.blb.mapper.TypeComMapper;
import com.blb.service.IComImgService;
import com.blb.service.ICommodityService;
import com.blb.service.ITypeComService;
import com.blb.utils.SessionUtils;
import com.blb.utils.UUIDUtils;
import com.mysql.jdbc.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuzhuo
 * @since 2019-07-11
 */
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements ICommodityService {
	@Autowired
	private CommodityMapper commodityMapper;
	@Autowired
	private TypeComMapper typeComMapper;
	@Autowired
	private ComImgMapper comImgMapper;
	@Autowired
	private IComImgService comImgService;
	@Autowired
	private ITypeComService typeComService;
	
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public String add(Commodity commodity, String comtypes, String dimg) throws Exception {
		commodity.setId(UUIDUtils.getID());
		commodity.setCreateUser(SessionUtils.getUserName());
		commodity.setCreateTime(new Date());
		commodity.setAddTime(new Date());
		commodityMapper.insert(commodity);
		
		if(!StringUtils.isNullOrEmpty(comtypes)){
			String[] comArr = comtypes.split(",");
			for (String comtype : comArr) {
				TypeCom typeCom = new TypeCom();
				typeCom.setTypeId(comtype);
				typeCom.setComId(commodity.getId());
				typeComMapper.insert(typeCom);
			}
		}
			String[] imgArr = dimg.split(",");
			System.out.println(imgArr.length);
			for (int i = 0; i < imgArr.length; i++) {
				ComImg comImg = new ComImg();
				comImg.setComId(commodity.getId());
				comImg.setImg(imgArr[i]);
				comImg.setSeq(i+1);
				comImgMapper.insert(comImg);
			}
		return "";
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void delete(List<String> ids) throws Exception {
		for (String id : ids) {
			commodityMapper.deleteById(id);
			typeComService.remove(new QueryWrapper<TypeCom>().eq("com_id", id));
			comImgService.remove(new QueryWrapper<ComImg>().eq("com_id", id));
		}
	}
}
